<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 陈风任 <491085389@qq.com>
 * Date: 2019-4-13
 */

namespace think\template\taglib\eyou;

use think\Db;
use think\Cache;
use think\Config;
use think\Request;


/**
 * 提交订单
 */
load_trait('controller/Jump');
class TagSpsubmitorder extends Base
{ 
    use \traits\controller\Jump;

    /**
     * 会员ID
     */
    public $users_id = 0;
    public $users = [];
    public $usersTplVersion = '';
    
    //初始化
    protected function _initialize()
    {
        parent::_initialize();
        // 会员信息
        $this->users = session('users');
        $this->users_id = session('users_id');
        $this->users_id = !empty($this->users_id) ? $this->users_id : 0;
        $this->usersTplVersion = getUsersTplVersion();

        // 商城订单模型
        $this->shopOrderModel = model('ShopOrder');
        // 商城商品模型
        $this->shopGoodsModel = model('ShopGoods');
    }

    /**
     * 获取提交订单数据
     */
    public function getSpsubmitorder()
    {
        // 获取解析数据
        $querystr = input('param.querystr/s', '');
        $resultData = $this->shopOrderModel->getGoodsBuyPage($querystr, $this->users, true);
        $goodsList = !empty($resultData['goodsList']) ? $resultData['goodsList'] : [];
        $globalParam = !empty($resultData['globalParam']) ? $resultData['globalParam'] : [];
        // 优惠券数据
        $useFindCoupon = !empty($resultData['useFindCoupon']) ? json_encode($resultData['useFindCoupon']) : null;
// dump($resultData);exit;
        // 商品个数
        $globalParam['goodsListCount'] = count($goodsList);
        // 返回购物车
        $globalParam['returnCart'] = url('user/Shop/shop_cart_list');
        // 余额充值页面
        $globalParam['rechargeBalance'] = url('user/Pay/pay_account_recharge');
        // 余额开关
        $globalParam['payBalanceOpen'] = intval(getUsersConfigData('pay.pay_balance_open'));

        // 表单验证
        static $request = null;
        if (null == $request) $request = Request::instance();
        $token = $request->token('__token__');
        $globalParam['tokenValue'] = $token;

        // 计算余额支付
        if (!empty($this->users)) {
            $globalParam['usersScores'] = $this->users['scores'];
            $globalParam['usersMoney'] = unifyPriceHandle($this->users['users_money']);
            $globalParam['usersSurplusMoney'] = unifyPriceHandle(strval($this->users['users_money']) - strval($globalParam['orderAmount']));
        }

        // 积分抵扣逻辑
        $globalParam = $this->shopOrderModel->getUseScoreHandle($globalParam);

        // 是否开启支付方式
        $where = [
            'status' => 1
        ];
        // 手机端微信、小程序不查询支付宝配置
        if ((isMobile() && isWeixin()) || isWeixinApplets()) $where['pay_mark'] = ['NEQ', 'alipay'];
        // 查询支付配置
        $payApiList = Db::name('pay_api_config')->where($where)->order('pay_id asc')->select();
        $openPay = 0; // 0未开启支付，1已开启支付
        $paymentMethod = 1; // 0为在线支付，1为货到付款
        // 在线支付判断
        if (!empty($payApiList)) {
            foreach ($payApiList as $key => $value) {
                $PayInfo = unserialize($value['pay_info']);
                if ('wechat' == $value['pay_mark']) {
                    // 微信判断
                    if (isset($PayInfo['is_open_wechat']) && 0 === intval($PayInfo['is_open_wechat'])) {
                        $openPay = 1;
                        $paymentMethod = 0;
                        break;
                    }
                } else if ('alipay' == $value['pay_mark']) {
                    // 支付宝判断
                    if (isset($PayInfo['is_open_alipay']) && 0 === intval($PayInfo['is_open_alipay'])) {
                        $openPay = 1;
                        $paymentMethod = 0;
                        break;
                    }  
                }
            }
        }
        // 余额支付判断
        if (isset($PayInfo['is_open_alipay']) && 1 === intval($globalParam['payBalanceOpen'])) {
            $openPay = 1;
            $paymentMethod = 0;
        }
        $globalParam['payName'] = '';
        $globalParam['openPay'] = $openPay;
        $globalParam['paymentMethod'] = $paymentMethod;

        // 收货地址处理
        $globalParam['isWeChat'] = 0;
        $globalParam['isMobile'] = 0;
        $globalParam['shopAddAddr'] = " onclick=\"ShopAddAddress();\" ";
        $orderLinkArr['shop_add_address'] = url('user/Shop/shop_add_address');
        if (isWeixin() && isMobile()) {
            $globalParam['isWeChat'] = 1;
            $globalParam['isMobile'] = 1;
            $globalParam['addr_width'] = '100%';
            $globalParam['addr_height'] = '100%';
            $globalParam['shopAddAddr'] = " onclick=\"GetWeChatAddr();\" ";
            $orderLinkArr['shop_add_address'] = url('user/Shop/shop_get_wechat_addr');
        } else if (isMobile()) {
            $globalParam['isWeChat'] = 0;
            $globalParam['isMobile'] = 1;
            $globalParam['addr_width'] = '100%';
            $globalParam['addr_height'] = '100%';
        } else {
            if ('v3' == $this->usersTplVersion) {
                $globalParam['addr_width'] = '660px';
                $globalParam['addr_height'] = '363px';
            } else {
                $globalParam['addr_width'] = '350px';
                $globalParam['addr_height'] = '480px';
            }
        }
        // dump($globalParam);exit;
        $orderParamArr = json_encode($globalParam);

        // 链接数组
        $orderLinkArr['shopCentre'] = url('user/Shop/shop_centre');
        $orderLinkArr['shop_del_address']  = url('user/Shop/shop_del_address');
        $orderLinkArr['shopEditAddress'] = url('user/Shop/shop_edit_address');
        $orderLinkArr['eyouOrderSubmit'] = url('user/Shop/eyou_order_submit', ['_ajax' => 1]);
        $orderLinkArr['eyouInquiryFreight']  = url('user/Shop/eyou_inquiry_freight', ['_ajax' =>1 ]);
        $orderLinkArr['eyouOrderSelectCoupon'] = url('user/Shop/eyou_order_select_coupon', ['querystr' => $querystr]);
        // dump($orderLinkArr);exit;
        $orderLinkArr = json_encode($orderLinkArr);

        // 系统版本号
        $version = getCmsVersion();
        // 会员模板版本号
        if (empty($this->usersTplVersion) || 'v1' == $this->usersTplVersion) {
            $jsfile = "tag_spsubmitorder.js";
        } else {
            $jsfile = "tag_spsubmitorder_{$this->usersTplVersion}.js";
        }
        // 循环中第一个数据带上JS代码加载
        $srcurl = get_absolute_url("{$this->root_dir}/public/static/common/js/{$jsfile}?t={$version}");

        $globalParam['hidden'] = <<<EOF
<script type="text/javascript">
    var orderLinkArr = {$orderLinkArr};
    var orderParamArr = {$orderParamArr};
    var useFindCoupon = {$useFindCoupon};
</script>
<script language="javascript" type="text/javascript" src="{$srcurl}"></script>
EOF;
        $result = [
            'list' => $goodsList,
            'data' => $globalParam,
        ];
        // dump($result);exit;
        return $result;
    }
}